
var CONF = {
	ajaxUrl: 		null,
	createOffer: 	null,
	listOffer: 		null,
	updateOffer: 	null,
	deleteOffer: 	null,
	createExtra: 	null,
	listExtra: 		null,
	updateExtra: 	null,
	deleteExtra: 	null,
	remoteExtraFromOffer: null,
	addExtraToOffer: null,
	availableExtras: null,
	init: function() { 
		CONF.createOffer 			= CONF.ajaxUrl + '/jtableCreateOffer';
		CONF.listOffer 				= CONF.ajaxUrl + '/jtableReadOffer';
		CONF.updateOffer 			= CONF.ajaxUrl + '/jtableUpdateOffer';
		CONF.deleteOffer 			= CONF.ajaxUrl + '/jtableDeleteOffer';
		CONF.createExtra 			= CONF.ajaxUrl + '/jtableCreateExtra';
		CONF.listExtra 				= CONF.ajaxUrl + '/jtableReadExtra?offerId=';
		CONF.updateExtra 			= CONF.ajaxUrl + '/jtableUpdateExtra';
		CONF.deleteExtra 			= CONF.ajaxUrl + '/jtableDeleteExtra';
		CONF.removeExtraFromOffer 	= CONF.ajaxUrl + '/remove_extra_offer';
		CONF.addExtraToOffer 		= CONF.ajaxUrl + '/add_extra_offer';
		CONF.availableExtras 		= CONF.ajaxUrl + '/availableExtras';
	},
	setUrl: function(url) { CONF.ajaxUrl = url; }
};


$(document).ready(function() {
	
	CONF.setUrl(window.ajaxUrl);
	CONF.init();
	
	drawTable();
	tableEvents();
	tmp(null);
});


function tmp(data) {
	//console.log(window.testUrl);
}


/**
 * Draw the jtable with the offers
 */
function drawTable() {
	
	// localization
	var messages = {
		serverCommunicationError: 'Ocorreu um erro na comunicação com o servidor.',
	    loadingMessage: 'A carregar ...',
	    noDataAvailable: 'Sem dados!',
	    addNewRecord: '+ Adicionar Oferta',
	    editRecord: 'Editar Registo',
	    areYouSure: 'Tem a certeza?',
	    deleteConfirmation: 'Este registo será eliminado. Tem a certeza?',
	    save: 'Guardar',
	    saving: 'A guardar',
	    cancel: 'Cancelar',
	    deleteText: 'Eliminar',
	    deleting: 'A eliminiar',
	    error: 'Erro',
	    close: 'Fechar',
	    cannotLoadOptionsFor: 'Não foi possivel carregar as opções do campo {0}',
	    pagingInfo: 'Mostrando {0} até {1} de {2} registos',
	    canNotDeletedRecords: 'Não foi possivel eliminar {0} de {1} registos!',
	    deleteProggress: 'Eliminado {0} de {1} registos, processando...'
	};
	
	$('#TableContainer').jtable({
		
		// Options
		title:					'Ofertas',
		paging:					false,
		sorting:				false,
		deleteConfirmation:		true,
		dialogShowEffect:		'fade',	
	    dialogHideEffect:		'fade',
	    selectOnRowClick:		false,
	    selectingCheckboxes:	false,
	    selecting:				false,
	    multiselect:			false,
	    saveUserPreferences:	false, 
	    //openChildAsAccordion:	true,
	    messages: 				messages,
	
		// Actions
		actions: {
	        createAction: 	CONF.createOffer,
	        listAction: 	CONF.listOffer,
	        updateAction: 	CONF.updateOffer,
	        deleteAction: 	CONF.deleteOffer
		},
		
		// Fields
		fields: {
			id: {
				key:			true,
				edit:			false,
				create:			false,
				list:			false
			},
			//--- CHILD TABLE DEFINITION FOR "EXTRAS" --------
            Extras: {
                title: 		'',
                width: 		'5%',
                sorting: 	false,
                edit: 		false,
                create: 	false,
                display: 	function (offerData) {
                	
                	var extraData = null;
                	
                    //Create an image that will be used to open child table (for now ... only a link is used)
                    var $img = $('<div class="showChildTable"><a href="#" title="alterar dados dos extras desta oferta">Extras</a></div>');
                    
                    // Open child table when user clicks the image
                    $img.click(function () {
                    	
                        $('#TableContainer').jtable('openChildTable',
                                $img.closest('tr'),
                                {
                        			// Options
                                    title: 		'Extras',
                                    messages: {
                                    	addNewRecord: '+ Adicionar Extra'
                                    },
                                    
                                    // Actions
                                    actions: {
                                        createAction: 	CONF.createExtra,
                                        listAction: 	CONF.listExtra + offerData.record.id,
                                        updateAction: 	CONF.updateExtra,
                                        deleteAction: 	CONF.deleteExtra
                                    },
                                    // Fields
                                    fields: {
                                    	name: {
                            				title:			'Nome',
                            				width:			'50%',
                            				type:			'text',
                            				edit:			true,
                            	            create:			true,
                            	            list:			true,
                            	            display:	function(data) {
                            	            	extraData = data;
                            	            }
                            			},
                            			price: {
                            				title:			'Preco',
                            				width:			'10%',
                            				type:			'text',
                            				edit:			false,
                            	            create:			false,
                            	            list:			false
                            			},
                            			active: {
                            				title:			'Activo',
                            				width:			'10%',
                            	            type:			'checkbox',
                            	            values:			{'0':'no','1':'yes'},
                            	            setOnTextClick:	false,
                            	            defaultValue:	'1',
                            				//edit:			true,
                            				//create:		true,
                            				list:			false
                            			},
                            			description: {
                            				title:			'Descrição',
                            				width:			'50%',
                            				type:			'textarea',
                            				list:			true
                            			}
                                    },
                                    
                                    // Events
                                    recordsLoaded: 			function(event,data) {
                            			handleChildRowEvents(offerData,extraData);
                            		},
                            		recordAdded: 			function(event,data) {
                            		}
                                    
                                }, function (data) { // anonymous callback function called when the childtable is opened
                                	// load extras
                                    data.childTable.jtable('load');
                                });
                    });
                    
                    //Return image to show on the person row
                    return $img;
                }
            }, //--- END "EXTRA" CHILD TABLE ----------------
			
			name: {
				title:			'Nome',
				width:			'40%',
				type:			'text',
				edit:			true,
	            create:			true,
	            list:			true
			},
			price: {
				title:			'Preco',
				width:			'10%',
				type:			'text',
				edit:			true,
	            create:			true,
	            list:			true
			},
			numberOfClasses: {
				title:			'Aulas',
				width:			'5%',
				type:			'text',
				edit:			true,
	            create:			true,
	            list:			true
			},
			remainingClasses: {
				title:			'Aulas disponiveis',
				width:			'15%',
				type:			'text',
				edit:			false,
	            create:			false,
	            list:			false
			},
			level: {
				title:			'Nivel',
				width:			'10%',
				options:		{'beginner':'beginner','advanced':'advanced'},
				edit:			true,
	            create:			true,
	            list:			true
			},
			minPart: {
				title:			'Minimo de participantes',
				width:			'10%',
				edit:			true,
	            create:			true,
	            list:			true
			},
			maxPart: {
				title:			'Maximo de participantes',
				width:			'10%',
				edit:			true,
	            create:			true,
	            list:			true
			},	
			active: {
				title:			'Activo',
				width:			'10%',
	            type:			'checkbox',
	            values:			{'0':'no','1':'yes'},
	            setOnTextClick:	false,
	            defaultValue:	'1',
				edit:			true,
				create:			true,
				list:			true
			},
			description: {
				title:			'Descrição',
				width:			'15%',
				type:			'textarea',
				list:			false
			}
		},
		
		// Events
		recordsLoaded: 			function() {
			
		}
	});
	
	//call readOfferAction and load data from server into the table
	$('#TableContainer').jtable('load');
}



/**
 * handle events from buttons present in the child rows
 */
function handleChildRowEvents(offerData,extraData) {
	
	// remove all events except for the CLOSE button ('edit' and 'delete')
	$('.jtable-child-row button').not('.jtable-close-button').unbind('click');
	
	// EDIT
	$('.jtable-child-row .jtable-edit-command-button ').on('click',function(event) {
		
	});
	
	// DELETE
	$('.jtable-child-row .jtable-delete-command-button ').on('click',function(event) {
		
		var properties = {
			width:		400,
			height:		150,
			show: 		'fade',
			hide: 		'fade',
			resize:			function(event,ui) {
			},
			buttons: {
				"Ok": 		function() {
					
					$.getJSON(CONF.removeExtraFromOffer, 
						{
							offerId:	offerData.record.id,
							extraId:	extraData.record.id
						},
						function(response) {
							//console.log('response', response);
							//console.log('getJSON returned');
							$('.jtable-child-table-container').jtable('load');
						}
					);
					
					$(this).dialog("close");
				},
				"Cancelar":	function() {
					$(this).dialog("close");
				}
			}
		};
		
		$('#deleteExtraConfirmation').dialog(properties);
	});
	
	// NEW
	$('.jtable-child-row .jtable-bottom-panel .jtable-add-record a').on('click',function(event) {
		
		// stop events associated to this anchor
		event.stopPropagation();
		
		// dialog properties
		var properties = {
			width:		200,
			height:		200,
			show: 		'fade',
			hide: 		'fade',
			resize:			function(event,ui) {
			},
			buttons: {
				"Ok": 		function() {
					
					var extraId = $('select#extraList').val();
					
					$.getJSON(CONF.addExtraToOffer,
						{
							offerId:	offerData.record.id,
							extraId:	extraId
						},
						function(response) { //	handle the response from the server 
							
							// refresh child table
							$('.jtable-child-table-container').jtable('load');
						}
					);
					
					$(this).dialog("close");
				},
				"Cancelar":	function() {
					$(this).dialog("close");
				}
			}
		};
	
		$.getJSON(CONF.availableExtras,
			{
				offerId:	offerData.record.id,
				userId:		offerData.record.users_id
			},
			function(data) {
				
				if ( data ) {	
					
					var options = '';
					
					for ( var i = 0; i < data.length; i++) {
						options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
					}
					
					$('select#extraList').html(options);
					$('#createExtraDialog').dialog(properties);
				}
				else {			
				}
			}
		);
	});
	
	// test
	$('.jtable-child-row .jtable-bottom-panel span.jtable-add-record').on('click',function(event) {
		//event.stopPropagation();
		//event.preventDefault();
		//alert('span add record');
	});
}



/**
 * handle events from jtable here
 */
function tableEvents() {
	
	// NEW .... offer ... use built in jtable form or use a customized form
	$('#TableContainer .jtable-add-record a').on('click',function(event) {
		
		// disable events defined by jtable
		//event.stopPropagation();
		return;

		var properties = {
			width:		700,
			height:		420,
			show: 		'fade',
			hide: 		'fade',
			buttons: {
				"Ok": 		
				function() {
					
					var data = $('#createOfferDialog');
					
					var validate = $('#createOfferDialog').validationEngine('validate');
					
					if ( !validate )
						return;
					
					var name 		= data.find('#offerNameVal').val();
					var active 		= '1';
					
					if ( data.find('#offerActiveVal:checked').val() != undefined )
						active 		= '1';
					else
						active 		= '0';
					
					var description = data.find('#offerDescriptionVal').val();
					var minPart 	= data.find('#offerPartMinVal').val();
					var maxPart 	= data.find('#offerPartMaxVal').val();
					var numClasses 	= data.find('#offerNumberOfClassesVal').val();
					var price		= data.find('#offerPriceVal').val();
					var level		= data.find('#offerLevelVal').val();
					
					$('#TableContainer').jtable('addRecord', {
					    record: {
					        name: 				name,
					        price: 				price,
					        numberOfClasses:	numClasses,
					        level: 				level,
					        minPart: 			minPart,
					        maxPart: 			maxPart,
					        active: 			active,
					        description: 		description
					    },
					    clientOnly:			false,
					    animationsEnabled:	true,
					    //url:				window.ajaxUrl + '/createOfferProgrammatically', // url to update record, if not defined jtable default url will be used
					    success:	function(data) {
					    	console.log(data);
					    	//console.log('success');
					    },
					    error:		function() {
					    	console.log('error');
					    }
					});
					
					// reload table
					//$('#TableContainer').jtable('reload');
					$(this).dialog("close");
				}
			}
		};
			
		$("#createOfferDialog").dialog(properties);
	});
	
	$('#reloadButton').on('click', function() {
		$('#TableContainer').jtable('reload',
				function() {
			
					//alert('reloaded');
				}
		);
	});

	$('.jtable-command-button').on('click',function(event) {
		event.preventDefault();
		//alert('hello');
	});
	
	$('#tmpButton').on('click',function(event) {
		console.log('tmpButton');
	});
	
	$('#createOfferButton').on('click', function() {
		
		$('#TableContainer').jtable('addRecord', {
		    record: {
		        name: 'tmp name',
		        price: '90',
		        numberOfClasses: '2',
		        //remainingClasses: '2',
		        level: 'beginner',
		        minPart: '2',
		        maxPart: '4',
		        active: '1',
		        description: 'tmp description'
		    },
		    clientOnly:			true,
		    animationsEnabled:	true,
		    //url:				window.ajaxUrl + '/createOfferProgrammatically', // url to update record, if not defined jtable default url will be used
		    success:	function() {
		    },
		    error:		function() {
		    }
		});
	});
}


